package org.ykh.service.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import org.springframework.web.bind.annotation.ExceptionHandler;
import org.ykh.service.exception.BusinessException;
import org.ykh.service.result.Result;

import javax.servlet.http.HttpServletResponse;

import static org.ykh.service.result.SysCode.FAIL;


/**
 * @author ykh
 */
@RestControllerAdvice
@Slf4j
public class DisposeException {

    @ExceptionHandler({RuntimeException.class})
    @ResponseStatus//设置响应码
    public Result<?> exceptionHandler(RuntimeException exception) {
        log.error("抛出异常{}", exception.getMessage());
        exception.printStackTrace();
        return Result.error(FAIL.code, "失败");
    }


    @ExceptionHandler({BusinessException.class})
    public Result<?> businessExceptionHandler(BusinessException exception, HttpServletResponse response) {
        if (exception.getHttpState() != null) {
            response.setStatus(exception.getHttpState().value());
        }
        return Result.error(exception.getCode(), exception.getMessage());
    }
}
